package com.itheima.controller;


import com.itheima.exception.SystemException;
import com.itheima.pojo.Book;
import com.itheima.pojo.Result;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.NativeWebRequest;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;


@RestController//rest风格   被Spring管理
@RequestMapping("/books")//路径
public class BookController {
    @Autowired
    private BookService bookService;

    @GetMapping("/testException")
    public Result testException(){
        //System.out.println(1 / 0);//运行时异常自动抛出
        //假设这里IO异常找不到了,报异常(编译时期异常)
        try {
            new FileInputStream("d:/a/s/d.jpg");
        } catch (FileNotFoundException e) {
            //将编译时异常 包装成运行时异常抛出
            throw new SystemException(null,e);
        }
        return new Result("success",1);
    }

    @PostMapping
    public Result save(@RequestBody Book book) {
        if (bookService.save(book)){
            //添加成功
            return new Result("success",1);
        }else {
            //添加失败
            return new Result("添加失败",0);
        }

    }

    @PutMapping
    public Result update(@RequestBody Book book) {
        if (bookService.update(book)){
            //修改成功
            return new Result("success",1);
        }else {
            //修改失败
            return new Result("修改失败",0);
        }
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        if (bookService.delete(id)){
            //删除成功
            return new Result("success",1);
        }else {
            //删除失败
            return new Result("删除失败",0);
        }
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        return new Result(bookService.getById(id),1);
    }

    @GetMapping
    public Result getAll() {
        return new Result(bookService.getAll(),1);
    }
}
